//
//  YCLOauthViewController.swift
//  新浪微博01
//
//  Created by yaochunlin on 16/4/10.
//  Copyright © 2016年 yaochunlin. All rights reserved.
//

import UIKit
import SVProgressHUD


class YCLOauthViewController: UIViewController {
    
    override func loadView() {
        
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        
        view.backgroundColor = GlobalBGColor
        
        //获取url
        let urlString = OauthURL + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri
        //发送请求
        let request = NSURLRequest.init(URL: NSURL.init(string: urlString)!)
        //加载网页页面
        webView.loadRequest(request)
        
        SVProgressHUD.showWithStatus("正在加载页面")//无法消失
        SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.None)
        
        navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("autoFill"))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("cancel"))
    }
    
    @objc private func autoFill(){
        
        let js = "document.getElementById('userId').value = 'm18674160018_1@163.com';document.getElementById('passwd').value = 'yaochunlin11'"
        
        webView.stringByEvaluatingJavaScriptFromString(js)
        
    }
    
    @objc private func cancel(){
        
        //取消HUD
        SVProgressHUD.dismiss()
        
        //点击取消销毁控制器
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //懒加载webview
    private lazy var webView:UIWebView = UIWebView()
}

extension YCLOauthViewController: UIWebViewDelegate{
    
    //页面加载完成后调用
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    
    //是否加载某个URL
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL?.absoluteString
//        YCLPrint("webView是否要去加载一个请求\(urlString)")
        
        //判断是否是授权回调地址
        let isRedirectUrl = urlString?.hasPrefix(redirect_uri)
        if !(isRedirectUrl!) {
            
            return true
        }else{
            
            //query是get请求后面的东西
            let query = request.URL?.query
            let codeString = "code="
            
            if query!.hasPrefix(codeString) {
                //点击了授权按钮
                //截取字符串,获得code
                let code = (query! as NSString).substringFromIndex(codeString.characters.count)
//                YCLPrint(code)
                
//                //获得AccessToken
                YCLUserAccountViewModel.sharedUserAccountViewModel.getAccessToken(code, callBack: { (error) in
                    
                    if error != nil {
                    
                        YCLPrint("加载AccessToken出错了,\(error)")
                        
                        //若出错延迟一秒关闭授权界面
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), {
                            
                            self.cancel()
                            return
                        })

                    }
                    
//                    YCLPrint("加载成功")
                    self.cancel()
                    
                    //跳转到欢迎界面
                    (UIApplication.sharedApplication().delegate as? AppDelegate)?.switchViewController(YCLWelcomeViewController())
                })
                
            }else{
                
                //YCLPrint("点击了取消按钮")
                cancel()
            }
            return false
        }
        
    }
}
